package com.app.oasystem.service.impl;


import com.app.oasystem.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static com.app.oasystem.constant.UploadPictureStatic.*;


/**
 * 上传图片
 *
 * @author zhangbaobing
 * @date 2021/4/16
 */
@Service
@Slf4j
public class UploadService {

    @Value("${filePath}")
    String filePath;

    public Map<String, Object> uploadPicture(MultipartFile file) {
        Map<String, Object> respMap = new HashMap<>(16);
        try {
            if (file != null) {
                String originalName = file.getOriginalFilename();
                // commons-io-2.0.1.jar  extension   扩展名，如jpg、png
                String extension = FilenameUtils.getExtension(originalName);
                String uuid = UUIDUtil.getUUID();
                String fileName = uuid + POINT + extension;
                String filepath = filePath + fileName;
                //打印查看上传路径
                log.info("图片的上传路径为{[" + filepath + "]}");
                File destFile = new File(filepath);
                if (!destFile.getParentFile().exists()) {
                    destFile.getParentFile().mkdirs();
                }
                file.transferTo(destFile);
                respMap.put(UPLOAD_CODE, DEFAULT_CODE);
                respMap.put(UPLOAD_MSG, DEFAULT_MSG);
                Map<String, Object> data = new HashMap<>(16);
                fileName = "file/" + fileName;
                data.put(UPLOAD_SRC, fileName);
                data.put(UPLOAD_TITLE, "");
                respMap.put(UPLOAD_DATA, data);

                log.info("图片名称：" + fileName);

                return respMap;
            }
        } catch (Exception e) {
            log.error("图片上传出错：{[" + e.getMessage() + "]}");
        }
        respMap.put(UPLOAD_CODE, EXCEPTION_CODE);
        respMap.put(UPLOAD_MSG, DEFAULT_MSG);
        return respMap;
    }

}